package com.company.jrlz.service;

import com.company.jrlz.entity.AssembleWorkOrder;
import com.company.jrlz.entity.ProcessWorkOrder;
import com.company.jrlz.service.util.ExcelUtils;
import com.haulmont.cuba.core.EntityManager;
import com.haulmont.cuba.core.Persistence;
import com.haulmont.cuba.core.Transaction;
import com.haulmont.cuba.core.app.FileStorageAPI;
import com.haulmont.cuba.core.entity.Entity;
import com.haulmont.cuba.core.entity.FileDescriptor;
import com.haulmont.cuba.core.global.DataManager;
import com.haulmont.cuba.core.global.LoadContext;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Service(AssembleWorkOrderService.NAME)
public class AssembleWorkOrderServiceBean implements AssembleWorkOrderService {

    @Inject
    private Persistence persistence;

    @Inject
    private DataManager dataManager;

    @Inject
    private FileStorageAPI fileStorageAPI;

    @Override
    public void inData(AssembleWorkOrder assembleWorkOrder) {
        insert(assembleWorkOrder);
    }


    //    导入excel数据
    @Override
    public String importData(File file, FileDescriptor fd, String fdname) {
        List<AssembleWorkOrder> assembleWorkOrderList = null;
        try {
            byte[] bytes = fileStorageAPI.loadFile(fd);

            ByteArrayInputStream in = new ByteArrayInputStream(bytes);

            assembleWorkOrderList = ExcelUtils.readMultipartFile(in, AssembleWorkOrder.class,fdname);//获取excel内容
            String a=excelSheetTop(bytes);//获取excel表头进行逻辑处理
            if(!a.equals("")){
                return a;
            }else {
//                System.out.println("车型"+processWorkOrderList.size());
                if(assembleWorkOrderList.size()>0){
                    if(      assembleWorkOrderList.get(0).getProjectCode().equals("")&&
                            assembleWorkOrderList.get(0).getSupportModel().equals("")&&
                            assembleWorkOrderList.get(0).getUprightModel().equals("")&&
                            assembleWorkOrderList.get(0).getBatchNum().equals("")&&
                            assembleWorkOrderList.get(0).getStartTime().equals("")&&
                            assembleWorkOrderList.get(0).getEndTime().equals(""))
                    {
                        return "表格数据不能为空";
                    }
                    //把获取的内容插入数据库中
                    for (int i=0;i<assembleWorkOrderList.size();i++) {
//                        System.out.println("车型"+processWorkOrder.getOrderStatus()+"");
                        for(int j=0;j<Integer.parseInt(assembleWorkOrderList.get(i).getNum());j++){
                            AssembleWorkOrder assembleWorkOrder = new AssembleWorkOrder();
                            assembleWorkOrder.setOrderStatus("未下发");
                            assembleWorkOrder.setOrderCode("GD"+System.currentTimeMillis());
                            assembleWorkOrder.setProjectCode(assembleWorkOrderList.get(i).getProjectCode());
                            assembleWorkOrder.setSupportModel(assembleWorkOrderList.get(i).getSupportModel());
                            assembleWorkOrder.setUprightModel(assembleWorkOrderList.get(i).getUprightModel());
                            assembleWorkOrder.setBatchNum(assembleWorkOrderList.get(i).getBatchNum());
                            assembleWorkOrder.setStartTime("");
                            assembleWorkOrder.setEndTime(assembleWorkOrderList.get(i).getEndTime());
                            inData(assembleWorkOrder);
                        }

                    }
                    return "导入成功";
                }else {
                    return "表格数据不能为空";
                }

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    //    插入数据
    public void insert(Entity transitRecord) {
        Transaction transaction = persistence.createTransaction();
        try {
            EntityManager entityManager = persistence.getEntityManager();
            entityManager.persist(transitRecord);
            transaction.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            transaction.end();
        }
    }
    /**
     * 获取Excel表头
     */
    public String excelSheetTop(byte[] byteArray){
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);

        try {
            // 创建一个临时文件
            File tempFile = File.createTempFile("temp", null);

            // 将ByteArrayInputStream对象的内容写入临时文件
            FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = byteArrayInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, length);
            }
            // 创建一个新的FileInputStream对象，指向临时文件
            FileInputStream fileInputStream = new FileInputStream(tempFile);
            // 清理临时文件
            fileOutputStream.close();
            tempFile.delete();
            // 使用转换后的FileInputStream对象进行其他操作
            // ...

            Workbook workbook = WorkbookFactory.create(fileInputStream);
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个Sheet
            Row headerRow = sheet.getRow(0); // 假设表头在第一行

            List<String> headers = new ArrayList<>();
            for (Cell cell : headerRow) {
                headers.add(cell.getStringCellValue());
            }

            // 打印表头
            for (String header : headers) {
//                System.out.print(header + "\t"+header.length());
            }

            if(headers.size()==6){
                if(!headers.get(0).trim().equals("工程编号")){
                    return "第一列工程编号名称不对";
                }
                if(!headers.get(1).trim().equals("支架型号")){
                    return "第二列支架型号不对";
                }
                if(!headers.get(2).equals("立柱型号（规格）")){
                    return "第三列立柱型号（规格）名称不对";
                }
                if(!headers.get(3).equals("批次号")){
                    return "第四列批次号名称不对";
                }
                if(!headers.get(4).equals("装配个数")){
                    return "第五列装配个数名称不对";
                }
                if(!headers.get(5).equals("计划完成时间")){
                    return "第六列计划完成时间名称不对";
                }
            }else {
                return "表格列数不对";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
}